package com.sccl.iottm.config;

import com.sccl.iottm.common.MyPasswordEncoder;
import com.sccl.iottm.filter.MyFilterSecurityInterceptor;
import com.sccl.iottm.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.session.HttpSessionEventPublisher;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.security.SpringSessionBackedSessionRegistry;

import javax.annotation.Resource;

/**
 * @Author Dave
 * @Date 2018/9/28
 * @Description Spring Security配置
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    private final Logger log = LoggerFactory.getLogger(SecurityConfig.class);
    @Autowired
    UserService userService;
    @Autowired
    private MyPasswordEncoder myPasswordEncoder;
    @Autowired
    MyFilterSecurityInterceptor myFilterSecurityInterceptor;


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(getAuthenticationProvider());
    }

    @Bean
    public AuthenticationProvider getAuthenticationProvider() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setUserDetailsService(userService);
        provider.setPasswordEncoder(passwordEncoder());
        return provider;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }


    //使用@Autowired会注入失败，不知道为啥。。
    @Resource
    FindByIndexNameSessionRepository sessionRepository;

    /**
     * 并发session配置sessionRegistry
     *
     * @return
     */
    @Bean
    public SessionRegistry getSessionRegistry() {
        return new SpringSessionBackedSessionRegistry(sessionRepository);
    }


    /**
     * 添加会话并发控制listener支持
     * 详情：https://docs.spring.io/spring-security/site/docs/4.1.0.RELEASE/reference/htmlsingle/#session-mgmt
     *
     * @return
     */
    @Bean
    public ServletListenerRegistrationBean httpSessionEventPublisher() {
        return new ServletListenerRegistrationBean(new HttpSessionEventPublisher());
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/index", "/", "/favicon.ico", "/config/sessionInvalid").permitAll()
                .anyRequest().authenticated() //任何请求,登录后可以访问
                .and()
                .formLogin()
                //登录任意访问
                .loginPage("/login").defaultSuccessUrl("/hello")
                .permitAll()
                .and()
                //注销任意访问
                .logout().logoutSuccessUrl("/login")
                .permitAll()
                //session 并发会话配置
                .and()
                .sessionManagement().maximumSessions(1).maxSessionsPreventsLogin(true).sessionRegistry(getSessionRegistry());

        //自定义过滤器 替代默认的FilterSecurityInterceptor
        http.addFilterBefore(myFilterSecurityInterceptor, FilterSecurityInterceptor.class);

    }


    @Override
    public void configure(WebSecurity web) throws Exception {
        //解决静态资源被拦截的问题
        web.ignoring().antMatchers("/static/**");
    }


}
